import imaplib
import email
import time
from bs4 import BeautifulSoup
from datetime import datetime, timedelta
import re
from icalendar import Calendar, Event, vCalAddress, vText
import subprocess


# 从邮件内容解析车票信息
def parse_event(text):

    # 提取时间
    begin_time = ''
    time_pattern = r"\d{4}年\d{2}月\d{2}日\d{2}:\d{2}"
    time_match = re.search(time_pattern, text)
    if time_match:
        time = time_match.group()
        # 解析为 datetime 对象
        begin_time = datetime.strptime(time, '%Y年%m月%d日%H:%M')
        print("时间:", begin_time)

    # 提取带有两个连字符（-）之间的字符串
    station = ''
    station_pattern = r"，([^，]+)-([^，]+)，"
    station_match = re.search(station_pattern, text)
    if station_match:
        start_station = station_match.group(1)
        end_station = station_match.group(2)
        station = start_station + "-" + end_station
        print("车站:", station)

    # 提取车次
    train = ''
    train_pattern = r"[A-Z]\d+次"
    train_match = re.search(train_pattern, text)
    if train_match:
        train = train_match.group()
        print("车次:", train)

    # 提取座位号
    seat = ''
    seat_pattern = r"\d+车\d+[A-Z]号"
    seat_match = re.search(seat_pattern, text)
    if seat_match:
        seat = seat_match.group()
        print("座位号:", seat)

    e = Event()
    e.add('uid', begin_time.strftime('%Y%m%d') + "-" + train)
    e.add('summary', train + ' ' + seat)
    e.add('location', station)
    e.add('description', 'Define the roadmap of our awesome project')
    e.add('dtstart', begin_time)
    e.add('dtend', begin_time)

    return e


# 写 ics 文件
def write_ics_file(event_list):
    # init the calendar
    cal = Calendar()
    cal.add('prodid', '-//My calendar product//example.com//')
    cal.add('version', '2.0')
    cal.add('X-WR-CALNAME', '火车日记')

    # Add the event to the calendar
    for e in event_list:
        cal.add_component(e)

    # Write to disk
    with open('rails.ics', 'wb') as f:
        f.write(cal.to_ical())
        f.close()


# 提交日历信息
def publish_ics():
    # 执行 git status 命令检查Git目录状态
    result = subprocess.run(['git', 'status', '--porcelain'], capture_output=True, text=True)
    # 获取命令输出结果
    output = result.stdout.strip()
    # 检查输出是否为空，如果为空则表示没有变化
    if len(output) != 0:
        subprocess.run(['git', 'add', '.'])
        subprocess.run(['git', 'commit', '-m', 'auto commit ics'])
        subprocess.run(['git', 'push'])
        print('publish_ics done')


# QQ 邮箱的 IMAP 服务器地址和端口
imap_server = 'imap.qq.com'
port = 993

# QQ 邮箱的用户名和密码
username = 'xx@qq.com'
password = 'xxx'

# 连接到 IMAP 服务器
imap = imaplib.IMAP4_SSL(imap_server, port)

# 登录到邮箱
imap.login(username, password)

# 选择邮箱文件夹（例如收件箱）
folder = 'INBOX'
imap.select(folder, readonly=True)

# work loop
while True:

    # 计算最近7天的日期范围
    today = datetime.today().date()
    three_days_ago = today - timedelta(days=7)

    # 搜索特定发件人的最新邮件
    status, response = imap.search(None, f'SINCE {three_days_ago.strftime("%d-%b-%Y")} FROM "12306@rails.com.cn"')

    # 获取搜索结果中的邮件 ID
    email_ids = response[0].split()
    # 反转，最新的在前
    email_ids = email_ids[::-1]

    event_list = []

    if email_ids:
        for email_id in email_ids:

            # 获取新邮件内容
            status, data = imap.fetch(email_id, '(RFC822)')

            # 解析原始邮件数据
            raw_email = data[0][1]
            msg = email.message_from_bytes(raw_email)

            # 提取邮件信息
            sendDate = msg['Date']

            # 将主题字符串转换为中文
            subject_bytes, subject_charset = email.header.decode_header(msg['Subject'])[0]
            subject = subject_bytes.decode(subject_charset)

            # 将发件人字符串转换为中文
            sender_bytes, sender_charset = email.header.decode_header(msg['From'])[0]
            if sender_charset:
                sender = sender_bytes.decode(sender_charset)
            else:
                sender = sender_bytes

            if '支付通知' not in subject and '兑现成功' not in subject:
                continue

            print('--------')
            print('email_id:', email_id)
            print('时间:', sendDate)
            print('发件人:', sender)
            print('主题:', subject)

            # 解码邮件内容
            if msg.is_multipart():
                for part in msg.walk():
                    content_type = part.get_content_type()
                    if content_type == 'text/html':
                        charset = part.get_content_charset()
                        html_content = part.get_payload(decode=True).decode(charset, errors='ignore')
                        soup = BeautifulSoup(html_content, 'html.parser')
                        email_content = soup.get_text()
                        # print(email_content)
                        event = parse_event(email_content)
                        event_list.append(event)
                    else:
                        print('content_type is', content_type)

    # 创建日历
    write_ics_file(event_list)

    # 发布
    publish_ics()

    # 每隔一段时间检查新邮件
    time.sleep(10)

# 关闭连接
imap.logout()